const express = require('express');
const router = express.Router();
const { authenticateAdmin } = require('../../middleware/auth');
const ResponseHelper = require('../../utils/response');
const LocalServicePrisma = require('../../models/LocalServicePrisma');
const ServiceCategoryPrisma = require('../../models/ServiceCategoryPrisma');

// 获取待审核列表
router.get('/pending-audit', authenticateAdmin, async (req, res) => {
  try {
    const {
      page = 1,
      pageSize = 10
    } = req.query;

    const searchParams = {
      page: parseInt(page),
      limit: parseInt(pageSize),
      audit_status: 'PENDING'
    };

    const result = await LocalServicePrisma.searchAll(searchParams);
    
    return ResponseHelper.paginated(
      res,
      result.services.map(service => service.toJSON()),
      {
        page: parseInt(page),
        pageSize: parseInt(pageSize),
        total: result.total,
        totalPages: Math.ceil(result.total / parseInt(pageSize))
      },
      '获取待审核列表成功'
    );
  } catch (err) {
    console.error('获取待审核列表失败:', err);
    return ResponseHelper.serverError(res, '获取待审核列表失败', err);
  }
});

// 审核统计
router.get('/audit-stats', authenticateAdmin, async (req, res) => {
  try {
    const stats = await LocalServicePrisma.getAuditStats();
    return ResponseHelper.success(res, stats, '获取审核统计成功');
  } catch (err) {
    console.error('获取审核统计失败:', err);
    return ResponseHelper.serverError(res, '获取审核统计失败', err);
  }
});

// 获取本地服务列表
router.get('/', authenticateAdmin, async (req, res) => {
  try {
    const {
      page = 1,
      pageSize = 10,
      status,
      audit_status,
      search,
      province,
      city,
      category_id
    } = req.query;

    const searchParams = {
      page: parseInt(page),
      limit: parseInt(pageSize),
      status,
      audit_status,
      keyword: search,
      province,
      city,
      category_id: category_id ? parseInt(category_id) : undefined
    };

    const result = await LocalServicePrisma.searchAll(searchParams);
    
    return ResponseHelper.paginated(
      res, 
      result.services.map(service => service.toJSON()), 
      {
        page: parseInt(page),
        pageSize: parseInt(pageSize),
        total: result.total,
        totalPages: Math.ceil(result.total / parseInt(pageSize))
      }, 
      '获取本地服务列表成功'
    );
  } catch (err) {
    console.error('获取本地服务列表失败:', err);
    return ResponseHelper.serverError(res, '获取本地服务列表失败', err);
  }
});

// 获取本地服务详情
router.get('/:id', authenticateAdmin, async (req, res) => {
  try {
    const { id } = req.params;
    const service = await LocalServicePrisma.findById(id, {
      includeUser: true,
      includeCategory: true
    });

    if (!service) {
      return ResponseHelper.notFound(res, '服务不存在');
    }

    return ResponseHelper.success(res, service.toJSON(), '获取服务详情成功');
  } catch (err) {
    console.error('获取服务详情失败:', err);
    return ResponseHelper.serverError(res, '获取服务详情失败', err);
  }
});

// 审核通过
router.put('/:id/approve', authenticateAdmin, async (req, res) => {
  try {
    const { id } = req.params;
    const { comment } = req.body;

    const service = await LocalServicePrisma.findById(id);
    if (!service) {
      return ResponseHelper.notFound(res, '服务不存在');
    }

    // 审核通过，立即发布
    await service.update({
      status: 'PUBLISHED',
      audit_status: 'APPROVED',
      audit_comment: comment || null,
      audit_time: new Date(),
      auto_publish_at: null // 清除自动发布时间
    });

    return ResponseHelper.success(res, service.toJSON(), '审核通过成功');
  } catch (err) {
    console.error('审核通过失败:', err);
    return ResponseHelper.serverError(res, '审核通过失败', err);
  }
});

// 审核拒绝
router.put('/:id/reject', authenticateAdmin, async (req, res) => {
  try {
    const { id } = req.params;
    const { comment } = req.body;

    if (!comment || !comment.trim()) {
      return ResponseHelper.error(res, '拒绝理由不能为空', 400);
    }

    const service = await LocalServicePrisma.findById(id);
    if (!service) {
      return ResponseHelper.notFound(res, '服务不存在');
    }

    // 审核拒绝，回到草稿状态
    await service.update({
      status: 'DRAFT',
      audit_status: 'REJECTED',
      audit_comment: comment,
      audit_time: new Date(),
      auto_publish_at: null // 清除自动发布时间
    });

    return ResponseHelper.success(res, service.toJSON(), '审核拒绝成功');
  } catch (err) {
    console.error('审核拒绝失败:', err);
    return ResponseHelper.serverError(res, '审核拒绝失败', err);
  }
});

// 更新服务状态
router.put('/:id/status', authenticateAdmin, async (req, res) => {
  try {
    const { id } = req.params;
    const { status } = req.body;

    if (!['DRAFT', 'PUBLISHED', 'OFFLINE'].includes(status)) {
      return ResponseHelper.error(res, '无效的状态值', 400);
    }

    const service = await LocalServicePrisma.findById(id);
    if (!service) {
      return ResponseHelper.notFound(res, '服务不存在');
    }

    await service.update({ status });

    return ResponseHelper.success(res, service.toJSON(), '状态更新成功');
  } catch (err) {
    console.error('状态更新失败:', err);
    return ResponseHelper.serverError(res, '状态更新失败', err);
  }
});

// 删除服务
router.delete('/:id', authenticateAdmin, async (req, res) => {
  try {
    const { id } = req.params;
    const service = await LocalServicePrisma.findById(id);

    if (!service) {
      return ResponseHelper.notFound(res, '服务不存在');
    }

    await service.hardDelete();
    return ResponseHelper.success(res, null, '删除服务成功');
  } catch (err) {
    console.error('删除服务失败:', err);
    return ResponseHelper.serverError(res, '删除服务失败', err);
  }
});

module.exports = router;